﻿﻿package com.glidecast.models
{
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLVariables;

	import flash.media.Sound;
	import flash.media.SoundTransform;
	import flash.media.SoundMixer;
	import flash.media.SoundChannel;
	
	import flash.events.Event;
	
	public class Audio extends EventDispatcher
	{
		public static var UPDATE:String='AudioUpdated';
		public static var COMPLETE:String='AudioDownloadComplete';
		
		private var snd:Sound = new Sound();
		private var channel:SoundChannel;
		private var pausePosition:int;
		
		public function Audio()
		{	
		}
		
		public function mute():void
		{
			trace(SoundMixer.soundTransform.volume.toString());
			if (SoundMixer.soundTransform.volume == 0)
			{
				volume = _volume;
				trace("vol is 0");
			}
			else
			{
				var st:SoundTransform = new SoundTransform();
				st.volume=0;
				SoundMixer.soundTransform=st;
				trace("???");
			}
		}
		private var _volume:Number=0;
		public function get volume():Number
		{
			return _volume;
		}
		public function set volume(s:Number):void
		{
			var st:SoundTransform = new SoundTransform();
			if ((s>0) && (s<1.01))
			{
				st.volume=s;
				_volume = s;//only storing this for mute purposes			
				SoundMixer.soundTransform=st;
				dispatchEvent(new Event(Audio.UPDATE));			
			}
		}
		
		private var _effect:String='';
		public function get effect():String
		{
			return _effect;
		}
		public function set effect(s:String):void
		{
			_effect=s;
			dispatchEvent(new Event(Audio.UPDATE));			
		}
		
		private var _url:String='';
		public function get url():String
		{
			return _url;
		}
		public function set url(s:String):void
		{
			_url=s;
			dispatchEvent(new Event(Audio.UPDATE));			
		}
		public function load():void
		{
			try
			{
				var urlReq:URLRequest = new URLRequest(this.url);
				snd = new Sound();
				snd.addEventListener("complete", audioLoaded);
				snd.load(urlReq);

			}
			catch(error:Error)
			{
				trace("audio load error: " + error);
				trace(error.getStackTrace());
			}
		}
		public function audioLoaded(evtObj:Event):void 
		{
			try
			{
				//broadcast this event.
				dispatchEvent(new Event(Audio.COMPLETE));
			}
			catch(error:Error)
			{
				trace("audioLoaded error " + error);
			}
		}
		public function play():void
		{
			try
			{
				channel = snd.play(0, int.MAX_VALUE);
			}
			catch(error:Error)
			{
				trace("play error " + error);
			}
		}
		public function pause():void
		{
			try
			{
				pausePosition = channel.position; 
				channel.stop();
			}
			catch(error:Error)
			{
				trace("pause error " + error);			
			}
		}
		public function resume():void
		{
			try
			{
				channel = snd.play(pausePosition);
			}			
			catch(error:Error)
			{
				trace("resume error " + error);			
			}
		}

	}
}
